package com.zhoukx.prototype.deepclone;

import java.io.*;

/**
 * @ClassName DeepProtoType
 * @Description:
 * @Author zhoukx
 * @Date 2020/8/6
 **/
public class DeepProtoType implements Serializable, Cloneable {
    public String name;  //String 属性
    public DeepCloneableTarget deepCloneableTarget; // 引用类型

    public DeepProtoType() {
    }

    @Override
    public String toString() {
        return "DeepProtoType{" +
                "name='" + name + '\'' +
                ", deepCloneableTarget=" + deepCloneableTarget +
                '}';
    }

    // 深拷贝 克隆方法 方式 一
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        // 这里对基本数据类型属性 完成克隆
        deep = super.clone();
        //对引用类型的属性，进行单独的处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
        return deep;
    }

    // 方式二  通过对象的序列化 实现深拷贝（推荐使用）
    public Object deepClone() {
        // 创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {

            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this); //  当前对象以流对象的方式输出

            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType copy = (DeepProtoType) ois.readObject();
            return copy;
        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
